/* $RCSFile: ModuleConfiguration.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/Configuration/Settings/ModuleConfiguration.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:27  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Configuration;
using System.Web;
using System.Web.Caching;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
using System.Globalization;

using AddonNice.Core;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes;
using AddonNice.Design;
using AddonNice.Diagnostics;
using AddonNice.Settings;

using Path2 =   AddonNice.Settings.Path;

namespace AddonNice.Configuration
{
    /// <summary>
    /// ModuleConfiguration Class encapsulates the detailed base configuration stored directly in each instanciated module record
    /// </summary>
	public class ModuleConfiguration 
	{
		public int          ModuleID            =   0;
		public int          ModuleDefID         =   0;
		public int          PageID              =   0;
		public int          CacheTime           =   0;
		public int          ModuleOrder         =   0;
        public int          ModuleSettingsID    =   0;
		public string       PaneName            =   "no pane";
		public string       ModuleTitle         =   string.Empty;
        public bool         ShowEveryWhere      =   false;
        public bool         SupportCollapsable  =   false;
        public string       DesktopSrc          =   string.Empty;
        public Guid         GuidID              =   Guid.Empty;
        public bool Admin                       =   false;

        /// <summary>
        /// String array of cache dependency files
        /// </summary>
        public ArrayList CacheDependency        =   new ArrayList();
        public bool Cacheable                   =   false;



        PortalSettings portalSettings
        {
            get
            {
                return (PortalSettings)HttpContext.Current.Items[StStr.strPortalSettings];
            }
        }
        

        string _strAdmin = string.Empty;
        string strAdmin
        {
            get
            {
                if (_strAdmin == string.Empty)
                {
                    _strAdmin = Config.InternalAdminRole + ";";
                }
                return _strAdmin;
            }
        }

        string _DBAllUser2 = string.Empty;
        string DBAllUser2
        {
            get
            {
                if (_DBAllUser2 == string.Empty)
                {
                    _DBAllUser2 = Config.InternallAllUsersRole + ";";
                }
                return _DBAllUser2;
            }
        }
        
        /// <summary>
		/// AuthorizedEditRoles
		/// </summary>
		string       _AuthorizedEditRoles   =   string.Empty;
        public string AuthorizedEditRoles
        {
            get
            {
                if ( string.IsNullOrEmpty(_AuthorizedEditRoles) )
                    _AuthorizedEditRoles    =   strAdmin;
                return _AuthorizedEditRoles;
            }
            set
            {
                _AuthorizedEditRoles        =   value;
            }
        }

        /// <summary>
		/// AuthorizedViewRoles
		/// </summary>
		string       _AuthorizedViewRoles   =   string.Empty;
        public string AuthorizedViewRoles
        {
            get
            {
                if ( string.IsNullOrEmpty(_AuthorizedViewRoles) )
                    _AuthorizedViewRoles    =   DBAllUser2;
                return _AuthorizedViewRoles;
            }
            set
            {
                _AuthorizedViewRoles        =   value;
            }
        }
		
        /// <summary>
		/// AuthorizedAddRoles
		/// </summary>
		string       _AuthorizedAddRoles    =   string.Empty;
        public string AuthorizedAddRoles
        {
            get
            {
                if ( string.IsNullOrEmpty(_AuthorizedAddRoles))
                    _AuthorizedAddRoles     =   strAdmin;
                return _AuthorizedAddRoles;
            }
            set
            {
                _AuthorizedAddRoles         =   value;
            }
        }

        /// <summary>
		/// AuthorizedDeleteRoles
		/// </summary>
		string       _AuthorizedDeleteRoles =   string.Empty;
        public string AuthorizedDeleteRoles
        {
            get
            {
                if ( string.IsNullOrEmpty(_AuthorizedDeleteRoles) )
                    _AuthorizedDeleteRoles  =   strAdmin;
                return _AuthorizedDeleteRoles;
            }
            set
            {
                _AuthorizedDeleteRoles      =   value;
            }
        }

        /// <summary>
		/// AuthorizedPropertiesRoles
		/// </summary>
		string       _AuthorizedPropertiesRoles =   string.Empty;
        public string AuthorizedPropertiesRoles
        {
            get
            {
                if ( string.IsNullOrEmpty(_AuthorizedPropertiesRoles))
                    _AuthorizedPropertiesRoles  =   strAdmin;
                return _AuthorizedPropertiesRoles;
            }
            set
            {
                _AuthorizedPropertiesRoles      =   value;
            }
        }
               
        /// <summary>
		/// AuthorizedDeleteModuleRoles 
		/// </summary>
		string       _AuthorizedDeleteModuleRoles   =   string.Empty;
        public string AuthorizedDeleteModuleRoles
        {
            get
            {
                if ( string.IsNullOrEmpty(_AuthorizedDeleteModuleRoles))
                    _AuthorizedDeleteModuleRoles    =   strAdmin;
                return _AuthorizedDeleteModuleRoles;
            }
            set
            {
                _AuthorizedDeleteModuleRoles        =   value;
            }
        }

        /// <summary>
		/// AuthorizedMoveModuleRoles
		/// </summary>
		string       _AuthorizedMoveModuleRoles     =   string.Empty;
        public string AuthorizedMoveModuleRoles
        {
            get
            {
                if ( string.IsNullOrEmpty(_AuthorizedMoveModuleRoles) )
                    _AuthorizedMoveModuleRoles      =   strAdmin;
                return _AuthorizedMoveModuleRoles;
            }
            set
            {
                _AuthorizedMoveModuleRoles          =   value;
            }
        }

        
        string _EntityName                          =   string.Empty;
        /// <summary>
        /// This is the entity specified in module settings, not the one from querystring
        /// </summary>
        public string EntityName
        {
            get
            {
                if (string.IsNullOrEmpty(_EntityName) && ModuleID != 0)
                {
				    if ( SettingsTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleConfiguration EntityName GET _EntityName null loading module moduleID: {0}",ModuleID),SettingsTraceSwitch.Sw.Info);
                    _EntityName                     =   new ModulesDB().GetSingleSettings(ModuleID,StStr.ModuleSettingsCRMEntityNameSettings);
				    if ( SettingsTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleConfiguration EntityName GET found: [{0}]",_EntityName),SettingsTraceSwitch.Sw.Info);
                }
                return _EntityName;
            }
        }

        #region Ctors
		
		public ModuleConfiguration()
		{
			if ( SettingsTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine("[V]ModuleConfiguration Ctor no parameters.",SettingsTraceSwitch.Sw.Info);
		}

        public ModuleConfiguration(SqlDataReader dr,bool doReadOnReader)
        {
            if (SettingsTraceSwitch.Sw.TraceVerbose)
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleConfiguration Ctor BEG SqlDataReader HasRows: {0}.", dr.HasRows), SettingsTraceSwitch.Sw.Info);
            ReadData(dr,doReadOnReader);
			if ( SettingsTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine("[V]ModuleConfiguration Ctor END.",SettingsTraceSwitch.Sw.Info);
        }

        public ModuleConfiguration(int ModuleID)
        {
			if ( SettingsTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleConfiguration Ctor BEG ModuleID: {0}.",ModuleID),SettingsTraceSwitch.Sw.Info);
            SqlDataReader dr                        =   null;
            try
            {
                dr                                  =    new ModulesDB().GetModuleConfigurationForModule(ModuleID);
                ReadData(dr,true);
            }
            catch (Exception ex)
            {
                if (SettingsTraceSwitch.Sw.TraceError)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ModuleConfiguration Ctor  ModuleID: {0}, ex: {1}",ModuleID,ex), SettingsTraceSwitch.Sw.Info);
                throw;
            }
            finally
            {
                if (dr != null)
                    dr.Close();
            }
			if ( SettingsTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine("[V]ModuleConfiguration Ctor END.",SettingsTraceSwitch.Sw.Info);
        }

        public void ReadData(SqlDataReader result,bool doReadOnReader)
        {
			if ( SettingsTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ModuleConfiguration ReadData SqlDataReader HasRows: {0}.",result.HasRows),SettingsTraceSwitch.Sw.Info);

            if ( !doReadOnReader || result.Read())
            {
                object myValue              =   null;
                try
                {
                    ModuleID                =   (int)result[StStr.DBModuleID];
                    ModuleDefID             =   (int)result[StStr.DBModuleDefID];
                    DesktopSrc              =   result[StStr.DBDesktopSrc].ToString();
                    Admin                   =   bool.Parse(result[StStr.DBAdmin].ToString());
                    PageID                  =   (int)result[StStr.DBPageID];
                    PaneName                =   (string)result[StStr.DBPaneName];
                    ModuleTitle             =   (string)result[StStr.DBModuleTitle];

                    myValue                 =   result[StStr.DBAuthorizedEditRoles];
                    AuthorizedEditRoles     =   Convert.IsDBNull(myValue) ? string.Empty : (string)myValue;

                    myValue                 =   result[StStr.DBAuthorizedViewRoles];
                    AuthorizedViewRoles     =   Convert.IsDBNull(myValue) ? string.Empty : (string)myValue;

                    myValue                 =   result[StStr.DBAuthorizedAddRoles];
                    AuthorizedAddRoles      =   Convert.IsDBNull(myValue) ? string.Empty : (string)myValue;

                    myValue                 =   result[StStr.DBAuthorizedDeleteRoles];
                    AuthorizedDeleteRoles   =   Convert.IsDBNull(myValue) ? string.Empty : (string)myValue;

                    myValue                 =   result[StStr.DBAuthorizedPropertiesRoles];
                    AuthorizedPropertiesRoles = Convert.IsDBNull(myValue) ? string.Empty : (string)myValue;

                    myValue                 =   result[StStr.DBAuthorizedMoveModuleRoles];
                    AuthorizedMoveModuleRoles = Convert.IsDBNull(myValue) ? string.Empty : (string)myValue;

                    myValue                 =   result[StStr.DBAuthorizedDeleteModuleRoles];
                    AuthorizedDeleteModuleRoles = Convert.IsDBNull(myValue) ? string.Empty : (string)myValue;

                    try
                    {
                        myValue             =   result[StStr.DBSupportCollapsable];
                    }
                    catch
                    {
                        myValue             =   DBNull.Value;
                    }
                    SupportCollapsable      =   DBNull.Value != myValue ? (bool)myValue : false;

                    try
                    {
                        myValue             =   result[StStr.DBShowEveryWhere];
                    }
                    catch
                    {
                        myValue             =   DBNull.Value;
                    }
                    ShowEveryWhere          =   DBNull.Value != myValue ? (bool)myValue : false;

                    CacheTime               =   (int)result[StStr.DBCacheTime];
                    ModuleOrder             =   (int)result[StStr.DBModuleOrder];
                    ModuleSettingsID        =   (int)result[StStr.DBModuleSettingsID];
                }
                catch (Exception exp)
                {
                    if (SettingsTraceSwitch.Sw.TraceError)
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ModuleConfiguration ReadData error reading data from reader ex: {0}", exp), SettingsTraceSwitch.Sw.Info);
                    throw;
                }
            }
            else
            {
                string msg                  =   string.Format("[E]ModuleConfiguration ReadData no record found ModuleID: {0}",ModuleID);
                if (SettingsTraceSwitch.Sw.TraceError)
                    Trace.WriteLine(msg, SettingsTraceSwitch.Sw.Info);
                throw new Exception(msg);
            }
			if ( SettingsTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine("[V]ModuleConfiguration ReadData END.",SettingsTraceSwitch.Sw.Info);
        }
        #endregion Ctors

		/// <summary>
		/// The GetModuleLoadingPath Method returns a string of
		/// the specified Module's path, which can be used to 
		/// Load this modules control into a page.
		/// </summary>
		public static string GetModuleLoadingPath(int xmoduleID)
		{
			string ControlPath			=	string.Empty;
			SqlDataReader dr			=	null;
			try
			{
				dr						=	new ModulesDB().GetModuleDefinitionByID(xmoduleID);
				if(dr.Read())
					ControlPath			=	Path2.WebPathCombine(Path2.ApplicationRoot, dr[StStr.DBDesktopSrc].ToString());
			}
			catch(Exception ex)
			{
				if ( SettingsTraceSwitch.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ModuleConfiguration GetModuleLoadingPath xmoduleID: {0} ex : {1}",xmoduleID, ex),SettingsTraceSwitch.Sw.Info);
				throw;
			}
			finally
			{
				if ( dr != null )
					dr.Close();
			}

			return ControlPath;
		}
    }
}
